package bingo.component.dhtmlxgrid;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

/**
 * 对用户授权进行认证的Tag, 如果用户没相应授权，则Tag中的Html代码全部不显示
 * 
 * @author martin
 */
@SuppressWarnings("unchecked")
public class GridTag extends TagSupport {

	private static final long serialVersionUID = 0L;

	private String gridName; // grid的名字，1、根据此名字构造javascript对象；2、grid所在的div也是据此构造，规则是gridName+"_div";3、分页div的名字也是据此构造，规则是gridName+"_pageDiv"
	private boolean showPageButton = true; // 是否显示分页按钮
	private String dataSourceSqlId; // 数据源SQLID
	private String configFileName; // 配置文件
	private String imagePath; // grid引用图片的路径
	private String skin = "bingo"; // grid的皮肤
	private String gridStyle; // grid样式
	private String requestParamPreprocessorId; // request参数预处理器Id
	private String dataProcessorId; // 行数据处理器
	private String pagesize = "10"; // 分页大小
	private boolean sortOnBackground = true; // 是否后台排序
	private String configParamPreprocessorId; // grid配置文件处理器Id
	private boolean enableAutoCookieSave = false; // cookie保存grid配置
	private String excelTemplateName = ""; // Excel模板名称
	private String exportExcelName = ""; // Excel导出文件名称
	private String envSqlId = ""; // grid环境变量来源sqlId
	private boolean loadOnFirst = true; // 是否在页面加载时自动加载数据
	private boolean showExportBtn = false;

	public boolean isLoadOnFirst() {
		return loadOnFirst;
	}

	public void setLoadOnFirst(boolean loadOnFirst) {
		this.loadOnFirst = loadOnFirst;
	}

	public String getEnvSqlId() {
		return envSqlId;
	}

	public void setEnvSqlId(String envSqlId) {
		this.envSqlId = envSqlId;
	}

	public String getExportExcelName() {
		return exportExcelName;
	}

	public void setExportExcelName(String exportExcelName) {
		this.exportExcelName = exportExcelName;
	}

	public String getExcelTemplateName() {
		return excelTemplateName;
	}

	public void setExcelTemplateName(String excelTemplateName) {
		this.excelTemplateName = excelTemplateName;
	}

	public boolean isEnableAutoCookieSave() {
		return enableAutoCookieSave;
	}

	public void setEnableAutoCookieSave(boolean enableAutoCookieSave) {
		this.enableAutoCookieSave = enableAutoCookieSave;
	}

	public String getConfigParamPreprocessorId() {
		return configParamPreprocessorId;
	}

	public void setConfigParamPreprocessorId(String configParamPreprocessorId) {
		this.configParamPreprocessorId = configParamPreprocessorId;
	}

	public boolean isSortOnBackground() {
		return sortOnBackground;
	}

	public void setSortOnBackground(boolean sortOnBackground) {
		this.sortOnBackground = sortOnBackground;
	}

	public String getPagesize() {
		return pagesize;
	}

	public void setPagesize(String pagesize) {
		this.pagesize = pagesize;
	}

	public String getRequestParamPreprocessorId() {
		return requestParamPreprocessorId;
	}

	public void setRequestParamPreprocessorId(String requestParamPreprocessorId) {
		this.requestParamPreprocessorId = requestParamPreprocessorId;
	}

	// ~ Methods
	// ========================================================================================================
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext
				.getRequest();
		String path = request.getContextPath();

		String gridContainer = this.getGridName() + "_Div";
		String pageContainer = this.showPageButton ? this.getGridName()
				+ "_pageDiv" : "";
		String gridCookieSetName = request.getRequestURI().substring(
				request.getRequestURI().lastIndexOf("/") + 1)
				+ this.getGridName();

		StringBuilder buffer = new StringBuilder();
		buffer.append("<div id='").append(gridContainer).append("' style='")
				.append(this.getGridStyle()).append("'>").append("</div>\n");
		if (this.isShowPageButton()) {
			buffer.append("<div id='").append(pageContainer).append(
					"' class='pagebutton'></div>").append("\n");
		}

		buffer.append("<script language='javascript'>").append("\n");
		buffer.append("try{").append("\n");
		buffer.append("var ").append(this.getGridName()).append(
				" = new dhtmlXGridObject('").append(gridContainer)
				.append("','").append(pageContainer).append("');").append("\n");
		buffer.append(this.getGridName()).append(".setImagePath('").append(
				this.getImagePath()).append("');").append("\n");
		buffer.append(this.getGridName()).append(".setSkin('").append(
				this.getSkin()).append("');").append("\n");
		// buffer.append(this.getGridName()).append(
		// ".enableRowsHover(true,'rowhover');").append("\n");
		buffer.append(this.getGridName()).append(".contextPath='").append(path)
				.append("'\n");
		buffer.append(this.getGridName()).append(".sqlId='").append(
				this.dataSourceSqlId).append("'\n");
		buffer.append(this.getGridName()).append(".excelTemplateName='")
				.append(this.excelTemplateName).append("'\n");
		buffer.append(this.getGridName()).append(".exportExcelName='").append(
				this.exportExcelName).append("'\n");
		if (StringUtils.isNotEmpty(this.pagesize)
				&& StringUtils.isNumeric(this.pagesize)) {
			buffer.append(this.getGridName()).append(".limited.size = ")
					.append(this.pagesize).append("\n");
		}
		buffer.append(this.getGridName()).append(".init();").append("\n");

		StringBuilder urlParams = getUrlParams();

		if (this.isEnableAutoCookieSave()) {
			buffer.append(this.getGridName()).append(".cookieName='").append(
					gridCookieSetName).append("';\n");
			buffer.append(this.getGridName()).append(".enableAutoSizeSaving('")
					.append(gridCookieSetName).append("');\n");
		}

		if (urlParams.length() > 0) {
			buffer.append(this.getGridName()).append(".requestParams='")
					.append(urlParams).append("';\n");
		}

		buffer.append(this.getGridName()).append(".xmlFileUrl = '")
				.append(path).append("/dhtmlxGridData?sqlId=").append(
						this.getDataSourceSqlId()).append("&envSqlId=").append(
						this.envSqlId).append("&configFileName=").append(
						this.getConfigFileName());

		if (StringUtils.isNotEmpty(this.requestParamPreprocessorId)) {
			buffer.append("&requestParamPreprocessorId=").append(
					this.requestParamPreprocessorId);
		}

		if (StringUtils.isNotEmpty(this.configParamPreprocessorId)) {
			buffer.append("&configParamPreprocessorId=").append(
					this.configParamPreprocessorId);
		}

		if (StringUtils.isNotEmpty(this.dataProcessorId)) {
			buffer.append("&dataProcessorId=").append(this.dataProcessorId);
		}
		if (urlParams.length() > 0) {
			buffer.append(urlParams);
		}
		buffer.append("';\n");

		if (isLoadOnFirst()) {
			buffer.append(this.getGridName()).append(".loadXML();\n");
		}

//		 buffer.append(this.getGridName()).append(".enableBlockSelection();")
//		 .append("\n");
		buffer.append(this.getGridName()).append(".showExportBtn=").append(this.showExportBtn)
			.append(";\n");		
		buffer.append(this.getGridName()).append(".sortOnBackground=").append(
				this.sortOnBackground).append(";\n");
		buffer.append("} catch(e) { alert(e);").append("}").append("\n")
				.append("</script>");
		JspWriter out = pageContext.getOut();
		try {
			out.println(buffer.toString());
		} catch (IOException e) {
			throw new JspTagException("I/O Error : " + e.getMessage());
		}
		return Tag.SKIP_BODY;
	}

	/**
	 * 添加request里的参数给URL
	 */
	private StringBuilder getUrlParams() {
		ServletRequest request = pageContext.getRequest();

		Enumeration<String> names = request.getParameterNames();
		StringBuilder urlParams = new StringBuilder();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String[] value = request.getParameterValues(name);
			if (value != null) {
				if (value.length > 1) {
					urlParams.append("&").append(name).append("=")
							.append(value);
				} else {
					urlParams.append("&").append(name).append("=").append(
							value[0]);
				}
			}
		}
		return urlParams;
	}

	public String getGridName() {
		return gridName;
	}

	public void setGridName(String gridName) {
		this.gridName = gridName;
	}

	public boolean isShowPageButton() {
		return showPageButton;
	}

	public void setShowPageButton(boolean showPageButton) {
		this.showPageButton = showPageButton;
	}

	public String getDataSourceSqlId() {
		return dataSourceSqlId;
	}

	public void setDataSourceSqlId(String dataSourceSqlId) {
		this.dataSourceSqlId = dataSourceSqlId;
	}

	public String getConfigFileName() {
		return configFileName;
	}

	public void setConfigFileName(String configFileName) {
		this.configFileName = configFileName;
	}

	public String getImagePath() {
		return imagePath;
	}

	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}

	public String getSkin() {
		return skin;
	}

	public void setSkin(String skin) {
		this.skin = skin;
	}

	public String getGridStyle() {
		return gridStyle;
	}

	public void setGridStyle(String gridStyle) {
		this.gridStyle = gridStyle;
	}

	public String getDataProcessorId() {
		return dataProcessorId;
	}

	public void setDataProcessorId(String dataProcessorId) {
		this.dataProcessorId = dataProcessorId;
	}

	public boolean isShowExportBtn() {
		return showExportBtn;
	}

	public void setShowExportBtn(boolean showExportBtn) {
		this.showExportBtn = showExportBtn;
	}	
}
